import React, { Component } from 'react'
import BlogList from '../../Components/BlogList'
import { RouteComponentProps } from 'react-router-dom';
import Article from '../../types/Article';
import { message } from 'antd';
import { queryArticlesOnCate } from '../../api/blog';

interface IProps extends RouteComponentProps<{ cateID: string }> { }
interface IState {
    loading: boolean;
    articles: Article[];
}

export default class Cates extends Component<IProps> {
    state = {
        loading: false,
        articles: []
    }

    refresh = async () => {
        this.setState({
            loading: true
        })
        const cateID = parseInt(this.props.match.params.cateID);
        if (!cateID) {
            //NaN且非0
            message.error('非法URL');
            this.props.history.push('/');
        }

        //请求对应分类的文章
        const data = await queryArticlesOnCate(cateID);
        if (!data) {
            return;
        }
        this.setState({
            articles: data,
            loading: false
        })
    }

    async componentDidUpdate(prevProps: IProps) {
        //发生变化（即选择另一个分类时）
        if (prevProps.match.params.cateID !== this.props.match.params.cateID) {
            this.refresh();
        }
    }
    async componentDidMount() {
        this.refresh();
    }
    render() {
        const { articles, loading } = this.state;
        return (
            <div>
                <BlogList articles={articles} loading={loading} />
            </div>
        )
    }
}
